package com.lanou.dllo.findfood.activity;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.lanou.dllo.findfood.R;
import com.lanou.dllo.findfood.fragment.CenterFragment;
import com.lanou.dllo.findfood.fragment.CookbookFragment;
import com.lanou.dllo.findfood.fragment.FindFragment;
import com.lanou.dllo.findfood.fragment.HomeFragment;
import com.lanou.dllo.findfood.share.AndroidShare;
import com.lanou.dllo.findfood.tools.ToastCommon;
import com.lanou.dllo.findfood.tools.UpdateManger;
import com.lanou.dllo.findfood.util.Constant;


//implements NavigationView.OnNavigationItemSelectedListener 抽屉部分内容
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private static final String SKIN_ID = "skin_id";//切换壁纸的图片id
    private TabHost mhost;
    private FragmentManager fm;
    private CenterFragment centerFragment;
    private HomeFragment homeFragment;
    private FindFragment findFragment;
    private CookbookFragment cookbookFragment;
    private TextView uName, user_name;
    private ImageView imageView;

    private ToastCommon toastCommom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mhost = (TabHost) findViewById(android.R.id.tabhost);
        mhost.setup();

        int id = getIntent().getIntExtra("fragid", 1);
        homeFragment = new HomeFragment();

        toastCommom = ToastCommon.createToastConfig();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        TabHost.TabSpec tab1 = mhost.newTabSpec("home");
        View view = getLayoutInflater().inflate(R.layout.tab_home_indicator, null);
        tab1.setIndicator(view);
        tab1.setContent(R.id.HomeView);
        mhost.addTab(tab1);


        TabHost.TabSpec tab2 = mhost.newTabSpec("发现");
        View view2 = getLayoutInflater().inflate(R.layout.tab_find_indicator, null);
        tab2.setIndicator(view2);
        tab2.setContent(R.id.FindView);
        mhost.addTab(tab2);

        TabHost.TabSpec tab3 = mhost.newTabSpec("菜谱");
        View view3 = getLayoutInflater().inflate(R.layout.tab_dary_indicator, null);
        tab3.setIndicator(view3);
        tab3.setContent(R.id.diaryView);
        mhost.addTab(tab3);

        TabHost.TabSpec tab4 = mhost.newTabSpec("个人");
        View view4 = getLayoutInflater().inflate(R.layout.tab_center_indicator, null);
        tab4.setIndicator(view4);
        tab4.setContent(R.id.PersonCenterView);
        mhost.addTab(tab4);

        imageView = (ImageView) findViewById(R.id.imageView);
        user_name = (TextView) findViewById(R.id.headeruser_Name);

        initFragment();


    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {

            //壁纸监听
            if ("bg0".equals(getSkinResourceName())) {
                setSkinResourceName("bg1");
            } else if ("bg1".equals(getSkinResourceName())) {
                setSkinResourceName("bg2");
            } else if ("bg2".equals(getSkinResourceName())) {
                setSkinResourceName("bg0");
            }
            refreshSkin();
            return true;
        }
        //菜单分享的功能
        if (id == R.id.share) {

        }
        //退出按钮的监听
        if (id == R.id.itemBack) {
            this.finish();
        }

        return super.onOptionsItemSelected(item);
    }

    private UpdateManger mUpdateManager;

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camara) {

            startActivity(new Intent(this, MyCenterActivity.class));
            // Handle the camera action
            //设置提醒的方法
        } else if (id == R.id.nav_gallery) {
            startActivity(new Intent(this, SetRemindActivity.class));
        } else if (id == R.id.nav_slideshow) {//版本更新
            mUpdateManager = new UpdateManger(this, Constant.apkUrl);
            mUpdateManager.checkUpdateInfo();
        }
        //对分享的按钮加监听
        else if (id == R.id.nav_share) {

// 创建退出对话框
            AlertDialog isExit = new AlertDialog.Builder(this).create();
            // 设置对话框标题
            isExit.setTitle("食尚生活");
            // 设置对话框消息
            isExit.setMessage("现在就去邀请好友一起开启美食之旅O(∩_∩)O");
            // 添加选择按钮并注册监听
            isExit.setButton("确定", listener);
            isExit.setButton2("取消", listener);
            // 显示对话框
            isExit.show();


        } else if (id == R.id.nav_send) {
            Intent intent_chages = new Intent(this, ChoseImageActivity.class);
            startActivity(intent_chages);

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void initFragment() {
        fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.HomeView, new HomeFragment());//首页
        ft.replace(R.id.FindView, new FindFragment());//发现
        ft.replace(R.id.PersonCenterView, new CenterFragment());//个人中心
        ft.replace(R.id.diaryView, new CookbookFragment());//美食菜谱

        ft.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshSkin();
    }

    /**
     * 更换皮肤
     * 1.点击更换皮肤快捷菜单后
     * 2.程序运行起来后
     */
    private void refreshSkin() {
        int skinId = getSkinResourceId();
        findViewById(R.id.drawer_layout).setBackgroundResource(skinId);
    }

    private int getSkinResourceId() {
        int skinId = R.mipmap.btn_check_off;//默认的背景图片
        String skinName = getSkinResourceName();
        if (skinName.equals("bg1")) {
            skinId = R.mipmap.app_bg_guide_two;
        } else if (skinName.equals("bg2")) {
            skinId = R.mipmap.app_bg_guide_one;
        }
        return skinId;
    }

    private String getSkinResourceName() {
        try {
            SharedPreferences preferences = getSharedPreferences("skinxml", Context.MODE_PRIVATE);
            return preferences.getString(SKIN_ID, "bg0");
        } catch (Exception e) {
            e.printStackTrace();
            return "bg0";
        }
    }

    private void setSkinResourceName(String skinName) {
        SharedPreferences preferences = getSharedPreferences("skinxml", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(SKIN_ID, skinName);
        editor.commit();
    }

    private boolean isExit = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    isExit = false;
                    break;
                default:
                    break;
            }
        }
    };


    //对物理键的监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                toastCommom.ToastShow(MainActivity.this,
                        (ViewGroup) findViewById(R.id.toast_layout_root), "在按一次退出程序");
                // 利用handler延迟发送更改状态信息
                handler.sendEmptyMessageDelayed(0, 2000);
            } else {
                finish();
                System.exit(0);
            }
        }
        return false;
    }

    /**
     * 监听对话框里面的button点击事件
     */
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
                    AndroidShare as = new AndroidShare(
                            MainActivity.this,
                            "我正在用一款很不错的APP,(*^__^*)邀请你一起使用,www.shishangshenghuo.com ",
                            "http://img6.cache.netease.com/cnews/news2012/img/logo_news.png");
                    as.show();
                    break;
                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
                    break;
                default:
                    break;
            }
        }
    };


}
